import BootstrapDialog from 'bootstrap3-dialog';
import WebUploader from 'webuploader';

import '../plugins/jquery.scrltab';
import '../plugins/ad/jquery.adfile';
import '../plugins/ad/jquery.adtip';
import '../../style/ad-add.less';
import '../../style/ad-module.less';

import fileEditHtml from '../../assets/partials/file/file-edit.html';

$.addAd = function dialog(groupId) {

    if (groupId == undefined) {
        groupId = $('#tree-panel').find(".selected").attr("data-id");
    }

    if (groupId == undefined) {
        alert("请在左边分组栏选择一个分组");
        return;
    }

    let uploaders = [];
    let removeFiles = [];

    let adDialog = $.dialog({
        title: "编辑广告",
        size: BootstrapDialog.SIZE_WIDE,
        message: $("<div>").html(fileEditHtml),
        onshow: function(dialog) {
            let body = dialog.getModalBody()[0];
            let $moduleTbody = $(body).find('tbody');
            let $zip = $(body).find('#zip').scrltab();

            $.myAjax({
                url: "ad/getAdConf.do",
                data: {
                    groupId: groupId
                },
                success: function(result) {
                    let data = result.data;

                    // logo
                    uploaders.push($zip.find("#ad-logo").adFile({
                        img: data.logo,
                        groupId: groupId,
                        module: "logo",
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));

                    // welcomePage
                    $zip.find("input[name='hotelName']").val(data.welcomePage.hotelName);
                    $zip.find("textarea[name='welcomeLg']").val(data.welcomePage.welcomeLg);
                    uploaders.push($zip.find("#welcomeImg").adFile({
                        img: data.welcomePage.welcomeImg,
                        groupId: groupId,
                        module: "welcome",
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));

                    // index
                    $zip.find("input[name='index-roomNum']").val(data.index.roomNum);
                    $zip.find("input[name='wifiName']").val(data.index.wifiName);
                    $zip.find("input[name='wifiPsw']").val(data.index.wifiPsw);
                    uploaders.push($zip.find("#index-qrcode").adFile({
                        img: data.index.qrCode,
                        groupId: groupId,
                        module: "index",
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));
                    uploaders.push($zip.find("#homeBroadcastArea").adFile({
                        img: data.index.homeBroadcastArea,
                        groupId: groupId,
                        module: "index",
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));
                    uploaders.push($zip.find("#indexCarousel").adFile({
                        img: data.index.indexCarousel,
                        groupId: groupId,
                        module: "index",
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));
                    $zip.find("#indexWord").adTip({
                        data: data.index.indexWord
                    });
                    $zip.find("input[name='rollCarousel']").val(data.index.rollCarousel);

                    // hotelIntr
                    uploaders.push($zip.find("#hotelIntr-imgs").adFile({
                        img: data.hotelIntr,
                        groupId: groupId,
                        module: "hotelIntr",
                        desc: true,
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));

                    // roomManage
                    $zip.find("input[name='roomNum']").val(data.roomManage.roomNum);
                    $zip.find("input[name='checkinTime']").val(data.roomManage.checkinTime);
                    $zip.find("input[name='checkoutTime']").val(data.roomManage.checkoutTime);
                    $zip.find("#guestKnow").adTip({
                        data: data.roomManage.guestKnow
                    });

                    // perTravel
                    uploaders.push($zip.find("#perTravel-imgs").adFile({
                        img: data.perTravel,
                        groupId: groupId,
                        module: "perTravel",
                        desc: true,
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));

                    // evalWord
                    $zip.find("#hotelServe").adTip({
                        data: data.evalWord.hotelServe
                    });
                    $zip.find("#funcAbnor").adTip({
                        data: data.evalWord.funcAbnor
                    });
                    uploaders.push($zip.find("#fix").adTip({
                        data: data.evalWord.fix,
                        lastPic: true,
                        groupId: groupId,
                        removeCallback: function(res) {
                            removeFiles.push(res);
                        }
                    }));

                }
            });

            //             let $tr = $(`<tr>
            //               <td>` + item.module + `</td>
            // <td><span>` + item.fileName + `</span><i class="icon icon-add"></i></td>
            //   <td>` + item.version + `</td>
            //            <td><input type="text" value="` + item.updateInfo + `" style="width: 100%"></td>
            //       </tr>`)
            //             $moduleTbody.append($tr);

        },
        submit: function(dialog) {

            let body = dialog.getModalBody()[0];
            let $zip = $(body).find('#zip');

            let indexCarousel = [];
            $zip.find("#indexCarousel").find("li:not(.add-icon)").each(function(index, item) {
                indexCarousel.push($(item).attr("data-file"));
            });

            let hotelIntr = [];
            $zip.find("#hotelIntr-imgs").find("li:not(.add-icon)").each(function(index, item) {
                let img = {
                    "img": $(item).attr("data-file"),
                    "desc": $(item).find("input").val()
                }
                hotelIntr.push(img);
            });

            let perTravel = [];
            $zip.find("#perTravel-imgs").find("li:not(.add-icon)").each(function(index, item) {
                let img = {
                    "img": $(item).attr("data-file"),
                    "desc": $(item).find("input").val()
                }
                perTravel.push(img);
            });

            let fix = $zip.find("#fix").adTip("getTips");
            fix.push($zip.find("#evalWord-fix").attr("data-file"));

            let data = {
                logo: $zip.find("#ad-logo").attr("data-file"),
                welcomePage: {
                    hotelName: $zip.find("input[name='hotelName']").val().trim(),
                    welcomeLg: $zip.find("textarea[name='welcomeLg']").val().trim(),
                    welcomeImg: $zip.find("#welcomeImg").attr("data-file"),
                },
                index: {
                    qrCode: $zip.find("#index-qrcode").attr("data-file"),
                    roomNum: $zip.find("input[name='index-roomNum']").val(),
                    wifiName: $zip.find("input[name='wifiName']").val(),
                    wifiPsw: $zip.find("input[name='wifiPsw']").val(),
                    rollCarousel: $zip.find("input[name='rollCarousel']").val(),
                    homeBroadcastArea: $zip.find("#homeBroadcastArea").attr("data-file"),
                    indexCarousel: indexCarousel,
                    indexWord: $zip.find("#indexWord").adTip("getTips")
                },
                hotelIntr: hotelIntr,
                roomManage: {
                    roomNum: $zip.find("input[name='roomNum']").val(),
                    checkinTime: $zip.find("input[name='checkinTime']").val(),
                    checkoutTime: $zip.find("input[name='checkoutTime']").val(),
                    guestKnow: $zip.find("#guestKnow").adTip("getTips")
                },
                perTravel: perTravel,
                evalWord: {
                    hotelServe: $zip.find("#hotelServe").adTip("getTips"),
                    funcAbnor: $zip.find("#funcAbnor").adTip("getTips"),
                    fix: fix
                }
            }

            let totalFile = 0;
            let cancelFile = 0;

            for (let uploader of uploaders) {
                cancelFile += uploader.getStats().cancelNum;
                let fileLength = uploader.getFiles().length;
                if (fileLength != 0) {
                    totalFile += uploader.getFiles().length;
                    uploader.upload();
                }
            }

            totalFile = totalFile - cancelFile;

            $.myAjax({
                url: "ad/writeHotelServiceJson.do",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    groupId: groupId,
                    removeFilePaths: removeFiles,
                    json: JSON.stringify(data)
                }),
                success: function(result) {
                    if (totalFile != 0) {
                        $.dialogShow({
                            title: "正在上传文件，请稍候……",
                            message: $(`<div class="progress" id="fileProgress">
                                      <div class="progress-bar" role="progressbar" aria-valuenow="60"
                                        aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
                                      </div></div>`),
                            onshown: function(progressDialog) {

                                let body = progressDialog.getModalBody()[0];

                                var $progressBar = $(body).find('.progress-bar');

                                let interval = setInterval(function() {

                                    let complete = 0;

                                    $.each(uploaders, function(index, item) {
                                        complete += item.getFiles("complete").length;
                                    });

                                    $progressBar.width((complete / totalFile) * 100 + "%");

                                    if (complete == totalFile) {
                                        clearInterval(interval);
                                        progressDialog.close();
                                        dialog.close();
                                    }

                                }, 100);
                            }
                        });
                    } else {
                        dialog.close();
                    }
                }
            });
        },
        onhidden: function(dialog) {
            var table = $(".table").DataTable();
            table.draw();
        }
    });

    $(document).on("click", ".evalWord div li", function(e) {
        $(".evalWord div li").removeClass("active");
        $(this).addClass("active");
        $(".evalWord").children("ul").hide();
        $("#" + $(this).attr("data-type")).show();
    });

}
